<template>
  <div class="vehicle-detail-page">
    <!-- 固定头部 -->
    <div class="page-header-fixed">
      <div class="header-left">
        <a class="back-link" @click="handleBack">
          <ArrowLeftOutlined />
          <span>返回车辆列表</span>
        </a>
        <div class="title-area">
          <h2>车辆详情</h2>
          <div class="plate-no">车牌号：{{ vehicle?.plateNumber }}</div>
        </div>
      </div>

      <a-space v-if="vehicle">
        <a-tag
          :color="getStatusColor(vehicle.vehicleStatus)"
          class="status-tag"
        >
          {{ getVehicleStatusLabel(vehicle.vehicleStatus) }}
        </a-tag>
        <a-button @click="handleEdit" v-permission="'vehicle:edit'">
          编辑
        </a-button>
        <a-popconfirm
          title="确定删除该车辆吗？"
          @confirm="handleDelete"
          v-permission="'vehicle:delete'"
        >
          <a-button danger>删除</a-button>
        </a-popconfirm>
      </a-space>
    </div>

    <!-- 可滚动内容区 -->
    <div class="page-content">
      <a-spin :spinning="loading">
        <!-- 车辆基本信息与证件信息 -->
        <a-card title="车辆信息" :bordered="false">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="车牌号">
              <span class="plate-number">{{ vehicle?.plateNumber }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="车辆类型">
              <a-tag color="blue">
                {{ getVehicleTypeLabel(vehicle?.vehicleType) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="车辆来源">
              <a-tag
                :color="vehicle?.vehicleSource === 'TEMP' ? 'orange' : 'green'"
              >
                {{ vehicle?.vehicleSource === "TEMP" ? "临时车" : "公司车" }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="品牌型号">
              {{ vehicle?.brandModel || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="载重">
              {{ vehicle?.loadCapacity }} 吨
            </a-descriptions-item>
            <a-descriptions-item label="容积">
              {{ vehicle?.volumeCapacity || "-" }} m³
            </a-descriptions-item>
            <a-descriptions-item label="购买日期">
              {{ formatDate(vehicle?.purchaseDate) }}
            </a-descriptions-item>
            <a-descriptions-item label="保险到期日期">
              <span :class="getExpireClass(vehicle?.insuranceExpireDate)">
                {{ formatDate(vehicle?.insuranceExpireDate) }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="年检到期日期">
              <span :class="getExpireClass(vehicle?.inspectionExpireDate)">
                {{ formatDate(vehicle?.inspectionExpireDate) }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="当前状态" :span="2">
              <a-tag :color="getStatusColor(vehicle?.vehicleStatus)">
                {{ getVehicleStatusLabel(vehicle?.vehicleStatus) }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 车主信息 -->
        <a-card title="车主信息" :bordered="false" style="margin-top: 24px">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="车主姓名">
              {{ vehicle?.ownerName || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="联系电话">
              {{ vehicle?.ownerPhone || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="身份证号">
              {{ vehicle?.ownerIdCard || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="驾驶证号">
              {{ vehicle?.ownerLicenseNumber || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="驾驶证类型">
              {{ vehicle?.ownerLicenseType || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="驾驶证到期">
              <span
                v-if="vehicle?.ownerLicenseExpireDate"
                :class="getExpireClass(vehicle?.ownerLicenseExpireDate)"
              >
                {{ formatDate(vehicle?.ownerLicenseExpireDate) }}
              </span>
              <span v-else>-</span>
            </a-descriptions-item>
            <a-descriptions-item label="车主地址" :span="2">
              {{ vehicle?.ownerAddress || "-" }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 备注信息 -->
        <a-card title="备注信息" :bordered="false" style="margin-top: 24px">
          <div class="remark-content">
            {{ vehicle?.remark || "无" }}
          </div>
        </a-card>
      </a-spin>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { ArrowLeftOutlined } from "@ant-design/icons-vue";
import type { Vehicle } from "@/types/vehicle";
import { getVehicleById, deleteVehicle } from "@/api/tenant/vehicle";
import { useDictionary } from "@/composables/useDictionary";
import dayjs from "dayjs";

const router = useRouter();
const route = useRoute();
const vehicleId = Number(route.params.id);

const loading = ref(false);
const vehicle = ref<Vehicle | null>(null);

// 使用字典
const { dictionaries: vehicleTypeDict, loadDictionaries: loadVehicleType } =
  useDictionary("VEHICLE_TYPE");
const { dictionaries: vehicleStatusDict, loadDictionaries: loadVehicleStatus } =
  useDictionary("VEHICLE_STATUS");

onMounted(async () => {
  await loadVehicleType();
  await loadVehicleStatus();
  await fetchVehicle();
});

// 获取车辆详情
const fetchVehicle = async () => {
  loading.value = true;
  try {
    const res = await getVehicleById(vehicleId);
    vehicle.value = res.data as any;
  } catch (error: any) {
    message.error(error.message || "获取车辆详情失败");
    router.back();
  } finally {
    loading.value = false;
  }
};

// 获取车辆类型标签
const getVehicleTypeLabel = (type: string | undefined): string => {
  if (!type) return "-";
  const dict = vehicleTypeDict.value.find((d) => d.dictCode === type);
  return dict?.dictLabel || type;
};

// 获取车辆状态标签
const getVehicleStatusLabel = (status: string | undefined): string => {
  if (!status) return "-";
  const dict = vehicleStatusDict.value.find((d) => d.dictCode === status);
  return dict?.dictLabel || status;
};

// 获取状态颜色
const getStatusColor = (status: string | undefined): string => {
  const colorMap: Record<string, string> = {
    AVAILABLE: "success",
    IN_USE: "processing",
    MAINTENANCE: "warning",
    DISABLED: "default",
  };
  return colorMap[status || ""] || "default";
};

// 格式化日期
const formatDate = (date: string | null | undefined): string => {
  if (!date) return "-";
  return dayjs(date).format("YYYY-MM-DD");
};

// 获取过期状态样式
const getExpireClass = (expireDate: string | null | undefined): string => {
  if (!expireDate) return "";
  const days = dayjs(expireDate).diff(dayjs(), "day");
  if (days < 0) return "expired";
  if (days < 30) return "expiring-soon";
  return "";
};

// 返回
const handleBack = () => {
  router.push("/tenant/vehicle");
};

// 编辑
const handleEdit = () => {
  router.push(`/tenant/vehicle/edit/${vehicleId}`);
};

// 删除
const handleDelete = async () => {
  try {
    await deleteVehicle(vehicleId);
    message.success("删除成功");
    router.push("/tenant/vehicle");
  } catch (error: any) {
    message.error(error.message || "删除失败");
  }
};
</script>

<style scoped>
.vehicle-detail-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

/* 固定头部 */
.page-header-fixed {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid var(--border-color);
  background: #fff;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 返回链接样式 */
.back-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--text-secondary);
  font-size: 14px;
  cursor: pointer;
  transition: all var(--transition-fast);
  width: fit-content;
}

.back-link:hover {
  color: var(--primary-color);
  gap: 8px;
}

.back-link span {
  text-decoration: none;
  transition: all var(--transition-fast);
}

.back-link:hover span {
  text-decoration: underline;
}

.title-area h2 {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 4px 0;
}

.plate-no {
  font-size: 13px;
  color: var(--text-secondary);
}

.status-tag {
  font-size: 14px;
  padding: 4px 12px;
  border-radius: var(--radius-md);
}

/* 可滚动内容区 */
.page-content {
  flex: 1;
  overflow: auto;
  padding: 0 16px 16px;
}

:deep(.ant-card) {
  box-shadow: var(--shadow-sm);
}

:deep(.ant-descriptions-bordered .ant-descriptions-item-label) {
  background: #fafafa;
  font-weight: 500;
  width: 140px;
}

.plate-number {
  font-weight: 600;
  font-size: 16px;
  color: var(--primary-color);
}

.remark-content {
  line-height: 1.8;
  color: var(--text-secondary);
  white-space: pre-wrap;
}

.expired {
  color: #ef4444;
  font-weight: 500;
}

.expiring-soon {
  color: #f59e0b;
  font-weight: 500;
}
</style>
